<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :class="{'mobile-el-dialog': showMobilePage}"
    class="normal-common-dialog-size"
    @closed="beClosed"
    @open="clearValidateInfo"
  >
    <div class="create-income-dialog">
      <div :style="{maxHeight: maxHeight}" :class="{'mobile-scroll': showMobilePage}" class="form-box scorll-bar">
        <div class="income-form-box">
          <Title :title="isEdit?'编辑收入项':'添加收入项'" style="margin-bottom:16px;"/>
          <div>
            <el-form ref="formRef" :model="queryData" :rules="rules" :label-width="labelWidth" :label-position="formAlign">
              <el-row>
                <el-col :span="colSpan">
                  <el-form-item label="收入项" prop="incomeItemId">
                    <selectWithUserLoad
                      ref="selectUser"
                      v-model="queryData.incomeItemObj"
                      :select-data-list="queryData.incomeItemObj ?[queryData.incomeItemObj] : []"
                      :multiple="false"
                      :loadmore-method="getItem()"
                      :disabled="isRelatedCost"
                      visible-change-data
                      class="width240"
                      placeholder="请选择收入项"
                      value-type="object"
                      extend-class="create-ip-order-select"
                      key-name="id"
                      label-name="name"
                      filterable
                      collapse-tags
                      @change="incomeItemObjChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="收入细项" prop="incomeDetail">
                    <el-select v-model="queryData.incomeDetail" :no-data-text="queryData.incomeItemId?'无数据':'请先选择收入项'" :disabled="isRelatedCost" placeholder="请选择收入细项" clearable filterable size="small" class="width240">
                      <el-option
                        v-for="item in incomeDetailOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="单价(元)" prop="unitPrice" class="is-required">
                    <el-input
                      v-model="queryData.unitPrice"
                      oninput="if(value>9999999999)value=9999999999;if(value<0)value=0"
                      name="unitPrice"
                      type="number"
                      placeholder="请输入单价"
                      size="small"
                      class="width240"
                      @blur="numberInputChange('unitPrice')"
                      @mousewheel.native.prevent
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="数量" prop="number" class="is-required">
                    <el-input
                      v-model.number="queryData.number"
                      oninput="if(value>99999)value=99999;if(value && value<1)value=1"
                      name="number"
                      type="number"
                      placeholder="请输入数量"
                      size="small"
                      class="width240"
                      @blur="numberInputChange('number', 1)"
                      @mousewheel.native.prevent
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="总价(元)" prop="totalPrice">
                    <el-input
                      v-model="queryData.totalPrice"
                      disabled
                      name="totalPrice"
                      type="number"
                      placeholder="=数量*单价"
                      size="small"
                      class="width240"
                      @mousewheel.native.prevent
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="税率" prop="taxRate">
                    <!-- <el-input
                  v-model="queryData.taxRate"
                  name="taxRate"
                  type="number"
                  placeholder="税率"
                  size="small"
                  class="width240"
                  @mousewheel.native.prevent
                >
                  <span slot="suffix" class="deductionRate">%</span>
                </el-input> -->
                    <el-autocomplete
                      v-model="queryData.taxRate"
                      :fetch-suggestions="taxRateQuerySearch"
                      :maxlength="12"
                      class="width240"
                      placeholder="请输入内容"
                      size="small"
                      @blur="numberInputChange('taxRate')"
                      @change="taxRateChange"
                      @select="handleTaxRateSelect"
                    >
                      <span slot="suffix" class="deductionRate">%</span>
                    </el-autocomplete>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="交付时间">
                    <el-date-picker
                      v-model="queryData.deliverTime"
                      :clearable="true"
                      type="date"
                      class="width240"
                      placeholder="请选择交付时间"
                      value-format="timestamp"
                      format="yyyy/MM/dd"
                      size="small"/>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="业绩月份">
                    <el-date-picker
                      v-model="queryData.month"
                      :clearable="true"
                      type="month"
                      class="width240"
                      placeholder="请选择业绩月份"
                      value-format="timestamp"
                      size="small"
                      format="yyyy/MM"/>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="款项应收时间">
                    <el-date-picker
                      v-model="queryData.receivableTime"
                      :clearable="true"
                      type="date"
                      class="width240"
                      placeholder="请选择款项应收时间"
                      value-format="timestamp"
                      format="yyyy/MM/dd"
                      size="small"/>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="分期月份">
                    <el-date-picker
                      v-model="queryData.incomeTimeRange"
                      type="monthrange"
                      size="small"
                      class="width240"
                      range-separator="-"
                      value-format="timestamp"
                      start-placeholder="开始月份"
                      end-placeholder="结束月份"
                      format="yyyy/MM"/>
                  </el-form-item>
                </el-col>
                <el-col :span="colSpan">
                  <el-form-item label="说明">
                    <el-input
                      v-model="queryData.explain"
                      :height="60"
                      style="font-size: 13px;"
                      type="textarea"
                      size="small"
                      resize="none"
                      maxlength="200"
                      placeholder="请描述该收入项内容，不超过200个字符"
                      class="width240"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
        <div v-if="isRelatedCost" class="income-form-box">
          <Title title="关联成本" style="margin-bottom:16px;"/>
          <el-form
            ref="costDataForm"
            :model="costData"
            :label-width="labelWidth"
            :label-position="formAlign"
            class="lineHeight32">
            <el-form-item label="成本来源">
              <el-select
                v-model="costData.costBelong"
                disabled
                class="width240"
                size="small">
                <el-option
                  v-for="item in mengliBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="成本项" prop="costItemId">
              <el-select
                v-model="costData.costItemName"
                class="width240"
                disabled
                size="small" />
            </el-form-item>
            <el-form-item class="label-999" label="成本类型:" prop="costType">
              <span v-if="costData.costType || costData.costType === 0">{{ costData.costType | costTypeFilter }}</span>
              <span v-else>--</span>
            </el-form-item>
            <el-form-item label="申请人" prop="proposer">
              <el-select
                v-model="costData.proposer"
                class="width240"
                disabled
                size="small" />
            </el-form-item>
            <el-form-item v-if="costData.costType !== 4" label="含税成本(元)" prop="taxCost">
              <el-input
                v-model="costData.taxCost"
                disabled
                placeholder="请输入金额"
                type="text"
                size="small"
                class="width240" />
            </el-form-item>
            <el-form-item v-if="costData.costType === 4" label="分成金额" prop="sharingPrice">
              <el-input
                v-model="costData.sharingPrice"
                disabled
                type="text"
                size="small"
                class="width240"/>
            </el-form-item>
            <el-form-item label="说明" prop="costDescription">
              <el-input
                v-model="costData.costDescription"
                :height="60"
                disabled
                type="textarea"
                size="small"
                maxlength="100"
                class="width240"/>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="costData.supplierName" disabled size="small" class="width240" />
            </el-form-item>
            <el-form-item label="可抵扣税率" prop="deductionRate">
              <el-input
                v-model="costData.deductionRate"
                :style="showMobilePage?'width:100px;':''"
                disabled
                type="text"
                size="small"
                class="width240">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
            <el-form-item label="分成比例">
              <el-input
                v-model="costData.dividePercent"
                :style="showMobilePage?'width:100px;':''"
                disabled
                type="text"
                size="small"
                class="width240"
                @input="dividePercentInput">
                <span slot="suffix" class="dividePercent">%</span>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button :loading="opeatorloading" type="primary" size="small" @click="handelOk()">确定</el-button>
        <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose()">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { getIcomeKindList, getIncomDetailList } from '@/api/config';
import { getRelatedCost } from '@/api/mengliOrder';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';
import mobileCreate from '@/mixins/mobileCreate';
import math from '@/utils/math';
import { costTypeFilter } from '@/filters/status';
import { percentRate } from '@/utils/numFormat';

export default {
  components: { Title, selectWithUserLoad, selectWithoutHttp },
  filters: { costTypeFilter },
  mixins: [mobileCreate],
  props: {
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      opeatorloading: false,
      isEdit: false,
      queryData: {
        incomeItemObj: {},
        incomeItemName: '', // 收入项名称
        incomeItemId: '',
        unitPrice: '', // 单价（元）
        number: 1, // 数量
        totalPrice: '', // 总结（元）
        explain: '', // 说明
        deliverTime: '', // 交付时间
        incomeDetail: '', // 收入细项
        month: '',
        receivableTime: '',
        taxRate: '6',
        incomeTimeRange: [],
        incomeStartTime: '',
        incomeEndTime: ''
      },
      costItemOptions: [],
      incomeDetailOptions: [],
      rules: {
        incomeItemId: [{ required: true, trigger: 'change', validator: this.validateNumber('请选择收入项') }],
        unitPrice: [{ required: true, trigger: 'blur', validator: this.validateNumber('请输入单价') }],
        number: [{ required: true, trigger: 'blur', validator: this.validateNumber('请输入数量') }],
        incomeDetail: [{ required: true, trigger: 'change', validator: this.validateNumber('请选择收入细项') }],
        taxRate: [{ required: true, trigger: 'blur', validator: this.validateNumber('请输入税率') }]
      },
      maxHeight: '',
      costData: {},
      autoDividePercent: 1,
      mengliBelongOptions: [
        { label: '商务订单', value: 2 },
        { label: '营销授权', value: 3 }
      ],
      dividePercent: null // 从供应商获取的分成比例
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    colSpan() {
      return this.showMobilePage ? 24 : (this.isRelatedCost ? 24 : 12);
    },
    labelWidth() {
      return this.showMobilePage ? '90px' : '110px';
    },
    isRelatedCost() {
      return !!(this.isEdit && ['IP衍生品', 'IP授权'].includes(this.queryData.incomeItemName) && this.costData && this.costData.linkIncomeItemNo);
    }
  },
  methods: {
    openDialog(data, index) {
      if (data) {
        this.queryData = JSON.parse(JSON.stringify(data));
        const timeWord = ['deliverTime', 'incomeStartTime', 'incomeEndTime'];
        for (const key of timeWord) {
          if (this.queryData[key]) {
            const timeData = this.queryData[key].toString().length === 10 ? Number(this.queryData[key]) * 1000 : this.queryData[key];
            this.$set(this.queryData, key, timeData);
          }
        }
        if (this.queryData.taxRate || this.queryData.taxRate === 0) {
          this.$set(this.queryData, 'taxRate', String(this.queryData.taxRate));
        }
        if (this.queryData.incomeStartTime && this.queryData.incomeEndTime) {
          this.$set(this.queryData, 'incomeTimeRange', [this.queryData.incomeStartTime, this.queryData.incomeEndTime]);
        } else {
          this.$set(this.queryData, 'incomeTimeRange', []);
        }
        this.$set(this.queryData, 'incomeItemObj', {
          id: this.queryData.incomeItemId,
          name: this.queryData.incomeItemName
        });
        this.isEdit = true;
        if (data.incomeItemId) {
          this.getIncomDetailList(data.incomeItemId);
        }
      } else {
        this.$set(this.queryData, 'taxRate', '6');
        this.$set(this.queryData, 'number', 1);
        this.isEdit = false;
      }
      const clientHeight = window.innerHeight;
      this.maxHeight = (clientHeight * 2.8) / 5 + 'px';
      this.dialogVisible = true;
    },
    // 获取关联成本
    getRelatedCost(id) {
      return new Promise((resolve, reject) => {
        getRelatedCost({ id }).then(res => {
          if (res.code !== 200) {
            reject(res.message);
          } else {
            if (res.data) {
              this.setMoneyData(res.data);
              this.costData = res.data;
              this.dividePercent = res.data.dividePercent;
            }
            resolve();
          }
        });
      });
    },
    // 金额处理分转元
    setMoneyData(data = {}) {
      const { taxCost: taxCostMoney, sharingPrice, dividePercent } = data;
      data.taxCost = !taxCostMoney ? taxCostMoney : this.showPrecise(taxCostMoney / 100);
      data.dividePercent = !dividePercent ? dividePercent : this.showPrecise(dividePercent * 100);
      data.sharingPrice = !sharingPrice ? sharingPrice : this.showPrecise(sharingPrice / 100);
    },
    // 精度处理
    showPrecise(num, precision = 12) {
      // 适用于长数值的直接展示 不适用于 两个浮点数的计算
      return +parseFloat(num.toPrecision(precision));
    },
    // 获取收入细项
    getIncomDetailList(id) {
      this.incomeDetailOptions = [];
      getIncomDetailList({ id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        if (res.data && res.data.items) {
          res.data.items.forEach(el => {
            this.incomeDetailOptions.push({
              value: el,
              label: el
            });
          });
        }
      }).catch(err => {
        console.log(err);
      });
    },
    validateNumber(msg) {
      return (rule, value, callback) => {
        if (value || value === 0) { callback(); } else { callback(new Error(msg)); }
      };
    },
    handelOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      this.opeatorloading = true;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (paramsObj.incomeTimeRange && paramsObj.incomeTimeRange.length === 2) {
            paramsObj.incomeStartTime = paramsObj.incomeTimeRange[0];
            paramsObj.incomeEndTime = paramsObj.incomeTimeRange[1];
          } else {
            paramsObj.incomeStartTime = '';
            paramsObj.incomeEndTime = '';
          }
          if (paramsObj.taxRate || paramsObj.taxRate === 0) paramsObj.taxRate = Number(paramsObj.taxRate);
          delete paramsObj.incomeTimeRange;
          delete paramsObj.incomeItemObj;
          if (this.isEdit) {
            this.$emit('editIcomeItem', { data: paramsObj });
          } else {
            this.$emit('addIcomeItem', paramsObj);
          }
          this.$nextTick(() => {
            if (this.isDetail && ['IP衍生品', 'IP授权'].includes(this.queryData.incomeItemName)) {
              this.$message.success('将按供应商分成比例生成成本，请点击成本列表查看');
            }
          });
          this.handleClose();
        } else {
          ElMessage.error('请检查信息是否完整');
          this.opeatorloading = false;
        }
      });
    },
    autoDividePercentChange(v) {
      this.autoDividePercent = v;
      // 自动时重置为从供应商获取的分成比例
      if (v) this.costData.dividePercent = this.dividePercent;
    },
    handleClose() {
      this.dialogVisible = false;
      this.autoDividePercent = 1;
      this.incomeDetailOptions = [];
      setTimeout(() => {
        this.opeatorloading = false;
        this.costData = null;
      }, 100);
    },
    beClosed() {
      this.queryData = {
        incomeItemName: '', // 收入项名称
        incomeItemId: '',
        unitPrice: '', // 单价（元）
        number: 1, // 数量
        totalPrice: '', // 总结（元）
        explain: '', // 说明
        deliverTime: '', // 交付时间
        incomeDetail: '', // 收入细项
        month: '',
        receivableTime: ''
      };
      this.clearValidateInfo();
    },
    mathTotalPrice() {
      const unitPrice = this.queryData.unitPrice;
      const number = this.queryData.number;
      if ((unitPrice || unitPrice === 0) && (number || number === 0)) {
        this.queryData.totalPrice = (math.multiply(unitPrice, number)).toFixed(2);
        this.handleTaxCost();
      } else {
        this.queryData.totalPrice = '';
      }
    },
    // 关联成本项的含税成本跟随变化
    handleTaxCost() {
      if (this.isRelatedCost) {
        this.costData.taxCost = (this.queryData.totalPrice / (1 + Number(this.queryData.taxRate) / 100) * (this.costData.dividePercent ? this.costData.dividePercent / 100 : 1)).toFixed(2);
      }
    },
    incomeItemObjChange(item) {
      this.queryData.incomeDetail = '';
      this.getIncomDetailList(item.id);
      this.queryData.incomeItemName = item.name;
      this.queryData.incomeItemId = item.id;
    },
    getItem() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.name = '';
          params.sourceId = 2;
          if (params.userName) params.name = params.userName;
          // getIcomeKindList
          getIcomeKindList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    numberInputChange(key, isInt = 0) {
      if (isInt === 1) {
        if (this.queryData[key]) this.queryData[key] = Number(this.queryData[key]).toFixed(0);
      } else {
        this.queryData[key] = Number(this.queryData[key]).toFixed(2);
      }
      this.mathTotalPrice();
    },
    clearValidateInfo() {
      const self = this;
      this.$nextTick(() => {
        self.$refs.formRef.clearValidate();
      });
    },
    taxRateQuerySearch(queryString, cb) {
      cb([
        { value: '6' },
        { value: '13' }
      ]);
    },
    handleTaxRateSelect(data) {
      this.$set(this.queryData, 'taxRate', data.value);
      this.handleTaxCost();
    },
    // 分成比例输入校验
    dividePercentInput(value) {
      this.costData.dividePercent = percentRate(value);
    },
    taxRateChange(value) {
      let str = value.replace(/[^\d.]/g, ''); // 只允许数字
      if (str) {
        str = Number(str).toFixed(2);
      }
      this.$set(this.queryData, 'taxRate', str);
    }
  }
};
</script>

<style lang="scss" scoped>
.create-income-dialog {
  &::v-deep {
    .el-input {
      .el-input__inner {
        width: 240px;
      }
    }
    .el-form-item__label {
      color: #666 !important;
    }
  }
  .dialog-footer{
    text-align: center;
  }
  .form-box {
    display: flex;
    max-height: 70vh;
    overflow: auto;
    padding-right: 6px;
    @include scrollBar($x: hidden, $y: auto, $width: 6px);
    ::v-deep .el-form-item {
      margin-bottom: 20px !important;
    }
  }
}
.width140 {
  width: 140px;
  ::v-deep .el-input__inner {
    width: 140px !important;
  }
}
.fb-switch {
  margin: 0 10px;
}
.width240{
  width: 240px;
}
.deductionRate {
  margin-right: 5px;
  color:#333;
}
.scorll-bar {
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
}
.mobile-scroll {
  &::v-deep {
    .el-form-item__label {
      line-height: 1.2 !important;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .el-input {
      width: 200px !important;
      .el-input__inner {
        width: 200px;
      }
    }
    .el-textarea__inner,.el-date-editor {
      width: 200px;
    }
  }
}
.mobile-el-dialog {
  .create-income-dialog {
    .form-box {
      flex-direction: column;
      max-height: 70vh;
      .width140 {
        ::v-deep .el-input__inner {
          width: 100px !important;
        }
      }
    }
  }
}
</style>
<style lang="scss">
/* .create-ip-order-select {
  width: 240px;
} */
</style>
